package com.css.zfzx.sjcj.modules.hddcGeomorphyline.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.repository.HddcGeomorphylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.repository.HddcGeomorphylineRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.repository.entity.HddcGeomorphylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.service.HddcGeomorphylineService;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.viewobjects.HddcGeomorphylineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeomorphyline.viewobjects.HddcGeomorphylineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-09
 */
@Service
public class HddcGeomorphylineServiceImpl implements HddcGeomorphylineService {

	@Autowired
    private HddcGeomorphylineRepository hddcGeomorphylineRepository;
    @Autowired
    private HddcGeomorphylineNativeRepository hddcGeomorphylineNativeRepository;

    @Override
    public JSONObject queryHddcGeomorphylines(HddcGeomorphylineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeomorphylineEntity> hddcGeomorphylinePage = this.hddcGeomorphylineNativeRepository.queryHddcGeomorphylines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeomorphylinePage);
        return jsonObject;
    }


    @Override
    public HddcGeomorphylineEntity getHddcGeomorphyline(String id) {
        HddcGeomorphylineEntity hddcGeomorphyline = this.hddcGeomorphylineRepository.findById(id).orElse(null);
         return hddcGeomorphyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphylineEntity saveHddcGeomorphyline(HddcGeomorphylineEntity hddcGeomorphyline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeomorphyline.setUuid(uuid);
        hddcGeomorphyline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeomorphyline.setIsValid("1");
        hddcGeomorphyline.setQualityinspectionStatus("0");
        hddcGeomorphyline.setExtends10("1");
        this.hddcGeomorphylineRepository.save(hddcGeomorphyline);
        return hddcGeomorphyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeomorphylineEntity> saveHddcGeomorphylineList(List<HddcGeomorphylineEntity> list) {
        for (HddcGeomorphylineEntity hddcGeomorphyline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeomorphyline.setUuid(uuid);
            hddcGeomorphyline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeomorphyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeomorphyline.setIsValid("1");
            hddcGeomorphyline.setQualityinspectionStatus("0");
            hddcGeomorphyline.setExtends10("1");
        }
        return hddcGeomorphylineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphylineEntity updateHddcGeomorphyline(HddcGeomorphylineEntity hddcGeomorphyline) {
        HddcGeomorphylineEntity entity = hddcGeomorphylineRepository.findById(hddcGeomorphyline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeomorphyline);
        hddcGeomorphyline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeomorphylineRepository.save(hddcGeomorphyline);
        return hddcGeomorphyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeomorphylines(List<String> ids) {
        List<HddcGeomorphylineEntity> hddcGeomorphylineList = this.hddcGeomorphylineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphylineList) && hddcGeomorphylineList.size() > 0) {
            for(HddcGeomorphylineEntity hddcGeomorphyline : hddcGeomorphylineList) {
                hddcGeomorphyline.setIsValid("0");
                hddcGeomorphyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphyline.setUpdateTime(new Date());
                this.hddcGeomorphylineRepository.save(hddcGeomorphyline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeomorphylineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeomorphylineEntity> yhDisasterEntities = hddcGeomorphylineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeomorphylineVO> list=new ArrayList<>();
        for (HddcGeomorphylineEntity entity:yhDisasterEntities) {
            HddcGeomorphylineVO yhDisasterVO=new HddcGeomorphylineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地貌线-线","地貌线-线",HddcGeomorphylineVO.class,"地貌线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeomorphylineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeomorphylineVO.class, params);
            List<HddcGeomorphylineVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeomorphylineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeomorphylineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeomorphylineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeomorphylineEntity yhDisasterEntity = new HddcGeomorphylineEntity();
            HddcGeomorphylineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeomorphyline(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeomorphylineEntity> hddcGeomorphylineList = this.hddcGeomorphylineRepository.queryHddcGeomorphylinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphylineList) && hddcGeomorphylineList.size() > 0) {
            for(HddcGeomorphylineEntity hddcGeomorphyline : hddcGeomorphylineList) {
                hddcGeomorphyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphyline.setIsValid("0");
                this.hddcGeomorphylineRepository.save(hddcGeomorphyline);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeomorphylineEntity> hddcGeomorphylineList = this.hddcGeomorphylineRepository.queryHddcGeomorphylinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphylineList) && hddcGeomorphylineList.size() > 0) {
            for(HddcGeomorphylineEntity hddcGeomorphyline : hddcGeomorphylineList) {
                hddcGeomorphyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphyline.setIsValid("0");
                this.hddcGeomorphylineRepository.save(hddcGeomorphyline);
            }
        }
    }

    @Override
    public List<HddcGeomorphylineEntity> findAll() {
        List<HddcGeomorphylineEntity> list=this.hddcGeomorphylineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeomorphylineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeomorphyCode")){
            str+="GeomorphyCode,";
        }
        if(!set.contains("GeomorphyName")){
            str+="GeomorphyName,";
        }
        if(!set.contains("GeomorphyType")){
            str+="GeomorphyType,";
        }
        if(!set.contains("GeomorphyDescription")){
            str+="GeomorphyDescription,";
        }
        if(!set.contains("Length")){
            str+="Length,";
        }
        if(!set.contains("Width")){
            str+="Width,";
        }
        if(!set.contains("Height")){
            str+="Height,";
        }
        if(!set.contains("MaxVerticalDisplacement")){
            str+="MaxVerticalDisplacement,";
        }
        if(!set.contains("MaxHorizenOffset")){
            str+="MaxHorizenOffset,";
        }
        if(!set.contains("MaxTDisplacement")){
            str+="MaxTDisplacement,";
        }
        if(!set.contains("Feature")){
            str+="Feature,";
        }
        if(!set.contains("CreateDate")){
            str+="CreateDate,";
        }
        if(!set.contains("IsSurfaceRuptureBelt")){
            str+="IsSurfaceRuptureBelt,";
        }
        if(!set.contains("FractureType")){
            str+="FractureType,";
        }
        if(!set.contains("Photo_AIID")){
            str+="Photo_AIID,";
        }
        if(!set.contains("Photo_ARWID")){
            str+="Photo_ARWID,";
        }
        if(!set.contains("PhotoViewingTo")){
            str+="PhotoViewingTo,";
        }
        if(!set.contains("Photographer")){
            str+="Photographer,";
        }
        if(!set.contains("nsb1")){
            str+="nsb1,";
        }
        if(!set.contains("nsb2")){
            str+="nsb2,";
        }
        if(!set.contains("nsb3")){
            str+="nsb3,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void savehddcGeomorphylineServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {

        if(list!=null&&list.size()>0){
            List<HddcGeomorphylineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeomorphylineEntity data = new HddcGeomorphylineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphycode(obs.get(2).toString());
                data.setGeomorphyname(obs.get(3).toString());
                data.setGeomorphytype(obs.get(4).toString());
                data.setGeomorphydescription(obs.get(5).toString());
                data.setLength(Double.valueOf(obs.get(6).toString()));
                data.setWidth(Double.valueOf(obs.get(7).toString()));
                data.setHeight(Double.valueOf(obs.get(8).toString()));
                data.setMaxverticaldisplacement(Double.valueOf(obs.get(9).toString()));
                data.setMaxhorizenoffset(Double.valueOf(obs.get(10).toString()));
                data.setMaxtdisplacement(Double.valueOf(obs.get(11).toString()));
                data.setFeature(obs.get(12).toString());
                data.setCreatedate(Integer.valueOf(obs.get(13).toString()));
                data.setIssurfacerupturebelt(Integer.valueOf(obs.get(14).toString()));
                data.setFracturetype(Integer.valueOf(obs.get(15).toString()));
                data.setPhotoAiid(obs.get(16).toString());
                data.setPhotoArwid(obs.get(17).toString());
                data.setPhotoviewingto(Integer.valueOf(obs.get(18).toString()));
                data.setPhotographer(obs.get(19).toString());
                data.setNsb1(obs.get(20).toString());
                data.setNsb2(obs.get(21).toString());
                data.setNsb3(obs.get(22).toString());
                data.setCommentInfo(obs.get(23).toString());

                String pstr=obs.get(0).toString();
                data.setExtends16("CGCS2000");
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeomorphylineList(datas);
        }

    }


    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeomorphylineEntity> hddcGeomorphylineEntityList = this.hddcGeomorphylineRepository.queryHddcGeomorphylineEntityByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphylineEntityList) && hddcGeomorphylineEntityList.size() > 0) {
            hddcGeomorphylineRepository.deleteAll(hddcGeomorphylineEntityList);
        }
    }

}
